from skimage.measure import compare_ssim
import argparse
import imutils
import cv2
import time
import numpy as np

#调用笔记本内置摄像头，所以参数为0，如果有其他的摄像头可以调整参数为1，2
cap=cv2.VideoCapture(0)

#调用时间直接复制：print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

while True:
    #从摄像头读取图片
    sucess,imageA=cap.read()
    
    #转为灰度图片
    gray=cv2.cvtColor(imageA,cv2.COLOR_BGR2GRAY)
    
    #显示摄像头，背景是灰度,打印时间。
    cv2.putText(gray,(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())),
                (20,400),cv2.FONT_HERSHEY_SIMPLEX,0.7,(255,255,255), 1,
                cv2.LINE_AA)
    
    cv2.imshow("imageA",gray)
    
    #保持画面的持续。
    k=cv2.waitKey(1)
    if k == 27:
        #通过esc键退出摄像
        cv2.destroyAllWindows()
        break
      
    elif __name__ == '__main__':
        #不断地判断。
         cv2.imwrite("1.png",imageA)
         time.sleep(0.2)
         sucess,imageB=cap.read()
         cv2.imwrite("2.png",imageB)
         #  cv2.destroyAllWindows()
         #  break

         # 将图像转换为灰度
         grayA = cv2.cvtColor(imageA, cv2.COLOR_BGR2GRAY)
         grayB = cv2.cvtColor(imageB, cv2.COLOR_BGR2GRAY)



         #计算两者之间的结构相似性指数
         #图像，确保返回差异图像
         (score, diff) = compare_ssim(grayA, grayB, full=True)
         diff = (diff * 255).astype("uint8")
         print("安全值: {}".format(score))

         if score<=0.95:
             print('危险！请赶紧撤离！')

         else:
             print('安全')
         
         #将差分图像设为阈值，然后查找等高线
         #获取两个不同输入图像的区域
         thresh = cv2.threshold(diff, 0, 255,
                 cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
         cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                 cv2.CHAIN_APPROX_SIMPLE)
         cnts = imutils.grab_contours(cnts)

         #环绕轮廓
         for c in cnts:
                 #计算轮廓的边界框，然后绘制
                 #两个输入图像上的边界框，表示两个
                 #图像不同
                 (x, y, w, h) = cv2.boundingRect(c)
                 cv2.rectangle(imageA, (x, y), (x + w, y + h), (0, 0, 255), 2)
                 cv2.rectangle(imageB, (x, y), (x + w, y + h), (0, 0, 255), 2)

         #图像降噪处理
         imageA = cv2.bilateralFilter(imageA,9,75,75)
         imageB = cv2.bilateralFilter(imageB,9,75,75)

         
         #显示输出图像
         cv2.imshow("Original", imageA)
         cv2.imshow("Modified", imageB)
         cv2.imshow("Diff", diff)
         cv2.imshow("Thresh", thresh)
         
cv2.waitKey(0)
#关闭摄像头
#cap.release()

